﻿using System.Collections.Generic;
using System.Windows;
using SilverBox.Helpers;

namespace SilverBox.Services
{
    /// <summary>
    /// Este servicio permite mantener una lista con el arbol visual de un control,
    /// ya que este arbol visual no es sensible de cambiar en sucesivas llamadas
    /// </summary>
    public class VisualTreeCache
    {
        private static VisualTreeCache _current = new VisualTreeCache();

        private readonly Dictionary<DependencyObject, List<DependencyObject>> _dic;

        private VisualTreeCache()
        {
            _dic = new Dictionary<DependencyObject, List<DependencyObject>>();
        }

        public static VisualTreeCache Current
        {
            get { return _current; }
        }

        public List<DependencyObject> this[DependencyObject obj]
        {
            get
            {
                List<DependencyObject> tmp = null;
                if (obj != null)
                {
                    if (!_dic.ContainsKey(obj))
                    {
                        AddVisualTree(obj);
                    }
                    tmp = _dic[obj];
                }
                return tmp;
            }
        }

        public void AddVisualTree(DependencyObject obj)
        {
            RemoveVisualTree(obj);
            var list = ControlTreeHelper.GetVisualTree(obj);
            _dic.Add(obj, list);
        }

        public void RemoveVisualTree(DependencyObject obj)
        {
            if (!_dic.ContainsKey(obj)) return;
            var tmp = _dic[obj];
            tmp.Clear();
            _dic.Remove(obj);
        }
    }
}